//
//  StwxDetailCell.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/10/24.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "StwxDetailCell.h"

#import <WebKit/WebKit.h>

@interface StwxDetailCell() <WKNavigationDelegate, UIWebViewDelegate>

/// viewModle
@property (nonatomic, readwrite, strong) StwxDetailItemViewModel *viewModel;

/// IBOutlet
@property (weak, nonatomic) IBOutlet UILabel* topLabel;
@property (weak, nonatomic) IBOutlet UIButton* lqBtn;
@property (weak, nonatomic) IBOutlet UILabel* titleLabel;
@property (weak, nonatomic) IBOutlet UILabel* nameLabel;
@property (weak, nonatomic) IBOutlet UILabel* sthLabel;
@property (weak, nonatomic) IBOutlet UIButton* go2Btn;
@property (weak, nonatomic) IBOutlet UIButton* focusBtn;
@property (weak, nonatomic) IBOutlet UILabel* sourceLabel;
@property (weak, nonatomic) IBOutlet UIView* contentWebView;
@property (weak, nonatomic) IBOutlet UIImageView* avatarImgView;
@property (weak, nonatomic) IBOutlet UIButton* commentTabBtn;
@property (weak, nonatomic) IBOutlet UIButton* zanTabBtn;
@property (weak, nonatomic) IBOutlet UIView* blockView;
@property (weak, nonatomic) IBOutlet UIView* seperateView;
@property (weak, nonatomic) IBOutlet UIView* tabBtnsView;

@property (strong, nonatomic) WKWebView* webView;
@property (strong, nonatomic) UIWebView* owebView;

@end

@implementation StwxDetailCell

- (void)awakeFromNib
{
    [super awakeFromNib];
    // Initialization code
    
    self.owebView = nil;
    self.webView = nil;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

#pragma mark - bind data
- (void)bindViewModel:(StwxDetailItemViewModel *)viewModel
{
    if (self.viewModel)
        return;
    
    self.viewModel = viewModel;
    
    BOOL isHaveDownload = [self.viewModel.downloadFileName isNotBlank];
    
    if (isHaveDownload)
    {
        if (self.owebView == nil)
        {
            UIWebView* curWV = [[UIWebView alloc] initWithFrame:(CGRect){0, 0, self.contentView.frame.size}];
            curWV.scrollView.bounces = NO;
            curWV.scrollView.scrollEnabled = NO;
            curWV.delegate = self;
            curWV.scalesPageToFit = YES;
            [self.contentWebView addSubview:curWV];
            
            [curWV mas_makeConstraints:^(MASConstraintMaker *make)
             {
                 make.edges.mas_equalTo(UIEdgeInsetsZero);
             }];
            
            self.owebView = curWV;
            
            [self.owebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.viewModel.downloadFilePath]]];
        }
    }
    else
    {
        if (self.webView == nil)
        {
            //注入JS以缩放网页，避免获取到的网页高度远超实际高度，出现超长空白页面
            NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
            WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
            WKUserContentController *wkUController = [[WKUserContentController alloc] init];
            [wkUController addUserScript:wkUScript];
            WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
            wkWebConfig.userContentController = wkUController;
            WKWebView* curWV = [[WKWebView alloc] initWithFrame:(CGRect) {0, 0, self.contentWebView.frame.size} configuration:wkWebConfig];
            curWV.scrollView.bounces = NO;
            curWV.navigationDelegate = self;
            [self.contentWebView addSubview:curWV];
            
            [curWV mas_makeConstraints:^(MASConstraintMaker *make)
             {
                 make.edges.mas_equalTo(UIEdgeInsetsZero);
             }];
            
            self.webView = curWV;
        }
    }
    
    self.topLabel.text = self.viewModel.top;
    self.titleLabel.text = self.viewModel.title;
    self.nameLabel.text = self.viewModel.name;
    self.sthLabel.text = self.viewModel.sth;
    self.sourceLabel.text = self.viewModel.source;
    [self.webView loadHTMLString:self.viewModel.content baseURL:[NSURL URLWithString:url_baseurl]];
    [self.commentTabBtn setTitle:self.viewModel.commentNum forState:UIControlStateNormal];
    [self.zanTabBtn setTitle:self.viewModel.goodNum forState:UIControlStateNormal];
    
    [self.avatarImgView yy_setImageWithURL:[NSURL URLWithString:self.viewModel.imgurl] placeholder:MHImageNamed(@"placeholderLogo")];
    
    self.lqBtn.layer.cornerRadius = self.lqBtn.frame.size.height/2.0f;
    self.lqBtn.layer.masksToBounds = YES;
    
    self.focusBtn.layer.cornerRadius = self.focusBtn.frame.size.height/2.0f;
    self.focusBtn.layer.masksToBounds = YES;
    
    bool isHaveCtrl = self.viewModel.isHaveCtrl;
    
    CGFloat seperateHeightValue = isHaveCtrl ? 10.0f : 0.0f;
    CGFloat tabBtnsViewHeightValue = isHaveCtrl ? 44.0f : 0.0f;
    
    for (NSLayoutConstraint* constraint in self.seperateView.constraints)
    {
        if (constraint.firstAttribute == NSLayoutAttributeHeight)
        {
            constraint.constant = seperateHeightValue;
            
            break;
        }
    }
    
    for (NSLayoutConstraint* constraint in self.tabBtnsView.constraints)
    {
        if (constraint.firstAttribute == NSLayoutAttributeHeight)
        {
            constraint.constant = tabBtnsViewHeightValue;
            
            break;
        }
    }
    
    @weakify(self);
    
    [[[self rac_signalForSelector:@selector(layoutSubviews)] takeUntil:[self rac_prepareForReuseSignal]] subscribeNext:^(id x)
    {
        @strongify(self);
        
        self.avatarImgView.layer.cornerRadius = self.avatarImgView.frame.size.height/2.0f;
        self.avatarImgView.layer.masksToBounds = YES;
    }];
    
    self.go2Btn.rac_command = self.viewModel.goUserSpaceCommand;
    
    RACSignal* commentTabBtnSignal = [[self.commentTabBtn rac_signalForControlEvents:UIControlEventTouchUpInside] map:^id(id value) {
        
        return @0;
    }];
    
    RACSignal* zanTabBtnSignal = [[self.zanTabBtn rac_signalForControlEvents:UIControlEventTouchUpInside] map:^id(id value) {
        
        return @1;
    }];
    
    RACSignal* tabSignal = [commentTabBtnSignal merge:zanTabBtnSignal];
    
    RAC(self.viewModel, tabIndex) = [tabSignal replay];
    
    [RACObserve(self.viewModel, tabIndex) subscribeNext:^(id x)
    {
        @strongify(self);
        
        NSInteger tabIndex = [x integerValue];
        
        @weakify(self);
        [UIView animateWithDuration:0.2f animations:^
        {
            @strongify(self);
            
            self.blockView.centerX = tabIndex==0 ? self.commentTabBtn.centerX : self.zanTabBtn.centerX;
        }];
    }];
}

#pragma mark - Delegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGFloat webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    
    for (NSLayoutConstraint* curConstraint in self.contentWebView.constraints)
    {
        if (curConstraint.firstAttribute == NSLayoutAttributeHeight)
        {
            curConstraint.constant = webViewHeight;
            
            break;
        }
    }
    
    // tableView reload
    [[self findTableView] reloadData];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation//这里修改导航栏的标题，动态改变
{
    @weakify(self);
    
    __block CGFloat webViewHeight;
    
    //获取内容实际高度（像素）@"document.getElementById(\"content\").offsetHeight;"
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error)
    {
        @strongify(self);
        
        // 此处js字符串采用scrollHeight而不是offsetHeight是因为后者并获取不到高度，看参考资料说是对于加载html字符串的情况下使用后者可以(@"document.getElementById(\"content\").offsetHeight;")，但如果是和我一样直接加载原站内容使用前者更合适
        //获取页面高度，并重置webview的frame
        webViewHeight = [result doubleValue];
        
        NSLog(@"web内容高度%f",webViewHeight); // 远高于实际值
        
        for (NSLayoutConstraint* curConstraint in self.contentWebView.constraints)
        {
            if (curConstraint.firstAttribute == NSLayoutAttributeHeight)
            {
                curConstraint.constant = webViewHeight;
                
                break;
            }
        }
        
        // tableView reload
        [[self findTableView] reloadData];
    }];
}

#pragma mark - 监听

@end
